package net.lovesrc.allin.biz.stl;

import com.alibaba.fastjson.JSONObject;
import com.zhouzhou.fastjava.BizException;
import com.zhouzhou.fastjava.http.MyHttpRequest;
import com.zhouzhou.fastjava.util.StringKit;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class StlRegisterService extends BaseStlService {

    private JSONObject getFreeIdCard() {
        String sql = "select * from t_id_card where worked = 1 and frontOcrStatus = 'normal' and backOcrStatus = 'normal' " +
                " and idCardNumber not in (select idCardNumber from t_stl_account where idCardNumber is not null) " +
                " and idCardNumber not in (select idCardNumber from t_stl_used_id) " +
                " limit 1";
        JSONObject row = queryForRow(jdbcTemplate, sql);
        if (row == null) {
            throw BizException.messageOf("无可用的身份证信息了");
        }
        return row;
    }


    private String doGetNewMobile() {
        for (; ; ) {
            String mobile = getMobileVerifyCodeWrapper().getPhone();
            if (jdbcTemplate.queryForObject("select count(1) from t_stl_account where mobile = ?", long.class, mobile) > 0) {
                getMobileVerifyCodeWrapper().addBlack(mobile);
                continue;
            }
            return mobile;
        }
    }

    public void syncStatus(String mobile) {
        try {
            this.doSyncStatus(mobile);
        } catch (Exception e) {
            logger.error("sync auth id error, {}", mobile, e);
            jdbcTemplate.update("update t_stl_account set idStatus = 'sync-failure', idTime = ?, idErrorMsg = ? where mobile = ?", new Date(), ExceptionUtils.getMessage(e), mobile);
        }
    }

    public void doSyncStatus(String mobile) {
        JSONObject row = queryForRow(jdbcTemplate, "select * from t_stl_account where mobile = ?", mobile);
        String idStatus = row.getString("idStatus");
        if ("success".equalsIgnoreCase(idStatus)) {
            return;
        }
        if (StringKit.notEqualsIgnoreCase("submitted", idStatus)) {
            return;
        }
        // 矿机
        List<JSONObject> kjs = getMyKjs(mobile);
        if (kjs.size() > 0) {
            jdbcTemplate.update("update t_stl_account set idStatus = 'success', idSuccessTime = ? where mobile = ?", new Date(), mobile);
            onAuthIdSuccess(mobile, row);
        } else {
            throw BizException.messageOf("暂无矿机");
        }
    }

    private void onAuthIdSuccess(String mobile, JSONObject row) {
        JSONObject resJson = this.post(mobile, "http://app.zaizhuji.cn/app/member/user.php?act=invite");
        String html = resJson.getString("content");
        Document doc = Jsoup.parse(html);
        String inviteCode = doc.selectFirst(".code b.fs").text();
        jdbcTemplate.update("update t_stl_account set inviteCode = ? where mobile = ?", inviteCode, mobile);
    }

    public String newRegister(String promotionCode) {

        if (StringUtils.isBlank(promotionCode)) {
            promotionCode = StringUtils.EMPTY;
        }
        CookieStore cookieStore = new BasicCookieStore();
        HttpClient httpClient = newHttpClientWithMyProxy(null, cookieStore);
        String mobile = doGetNewMobile();
        getMobileVerifyCodeWrapper().releasePhone(mobile);
        String verifyCode = RandomStringUtils.randomNumeric(4);
        JSONObject mobileModel = getOneMobileModel();
        JSONObject device = new JSONObject()
                .fluentPut("uuid", mobileModel.getString("deviceId"))
                .fluentPut("model", mobileModel.getString("model"))
                .fluentPut("vendor", mobileModel.getString("manufacturer"));
        String password = RandomStringUtils.randomAlphanumeric(8, 12);
        JSONObject regResJson = MyHttpRequest.post(httpClient, "http://app.zaizhuji.cn/app/dong.php")
                .param("act", "reg")
                .param("username", mobile)
                .param("mobile_phone", mobile)
                .param("dxm", verifyCode)
                .param("quhao", "+86")
                .param("invite_code", promotionCode)
                .param("password", password)
                .param("confirmpassword", password)
                .param("device", device)
                .executeUtilReturn200()
                .asJson();
        if (regResJson.toJSONString().contains("该手机已注册过了")) {
            getMobileVerifyCodeWrapper().addBlack(mobile);
            throw BizException.messageOf("该手机已注册过了");
        }
        JSONObject newRow = new JSONObject()
                .fluentPut("mobile", mobile)
                .fluentPut("verifyCode", verifyCode)
                .fluentPut("promotionCode", promotionCode)
                .fluentPut("password", password)
                .fluentPut("registerResText", regResJson.toJSONString())
                .fluentPut("device", device.toJSONString())
                .fluentPut("registerStatus", regResJson.getIntValue("status"));
        insertRow(jdbcTemplate, "t_stl_account", newRow);
        return mobile;
    }

    private JSONObject getOneMobileModel() {

        String manufacturer = jdbcTemplate.queryForObject("select manufacturer from (select distinct manufacturer from t_mobile_model) r order by rand() limit 1", String.class);
        JSONObject row = queryForRow(jdbcTemplate, "select * from t_mobile_model where manufacturer = ? order by rand() limit 1", manufacturer);
        if ("iOS".equalsIgnoreCase(row.getString("type"))) {
            row.put("deviceId", UUID.randomUUID().toString().toUpperCase());
        } else {
            row.put("deviceId", RandomStringUtils.randomNumeric(15));
        }
        return row;
    }

    public void authId(String mobile) {
        try {
            this.doAuthId(mobile);
        } catch (Exception e) {
            logger.error("auth id error, {}", mobile, e);
            jdbcTemplate.update("update t_stl_account set idStatus = 'failure', idTime = ?, idErrorMsg = ? where mobile = ?", new Date(), ExceptionUtils.getMessage(e), mobile);
        }
    }

    public synchronized void doAuthId(String mobile) {
        // 登录
        JSONObject row = queryForRow(jdbcTemplate, "select * from t_stl_account where mobile = ?", mobile);
        String idStatus = row.getString("idStatus");
        if ("success".equalsIgnoreCase(idStatus)) {
            return;
        }
        if ("submitted".equalsIgnoreCase(idStatus)) {
            return;
        }
        // 实名
        JSONObject idRow = getFreeIdCard();
        String realName = idRow.getString("realName");
        String idCardNumber = idRow.getString("idCardNumber");

        JSONObject resJson = this.postDong(mobile, "smrz_up",
                new JSONObject()
                        .fluentPut("shop_sfz", idCardNumber)
                        .fluentPut("shop_name", realName)
                        .fluentPut("shop_logo", StringUtils.EMPTY)
                        .fluentPut("shop_logo2", StringUtils.EMPTY)
        );
        JSONObject sets = new JSONObject()
                .fluentPut("idResText", resJson.toJSONString())
                .fluentPut("idCardNumber", idCardNumber)
                .fluentPut("realName", realName)
                .fluentPut("idStatus", "submitted")
                .fluentPut("idTime", new Date())
                .fluentPut("idResStatus", resJson.getIntValue("status"))
                .fluentPut("idResError", resJson.getIntValue("error"));
        updateRow(jdbcTemplate, "t_stl_account", sets, "mobile = ?", mobile);
    }

}
